<template>
    <el-breadcrumb :separator-icon="ArrowRight">
    <el-breadcrumb-item :to="{ path: '/' }">首页(登录)</el-breadcrumb-item>
    <el-breadcrumb-item>授权中心管理</el-breadcrumb-item>
    <el-breadcrumb-item>角色管理</el-breadcrumb-item>
  </el-breadcrumb>
    <div>
       <el-card style="margin-top: 10px;">
          <el-form :inline="true" :model="searchData" class="demo-form-inline">
    <el-form-item label="角色名称">
      <el-input v-model="searchData.RoleName" placeholder="角色名称" clearable />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="getRoles">查询</el-button>
      <el-button type="success" @click="addPermission">添加</el-button>
    </el-form-item>
  </el-form>
       </el-card>
       <el-card style="margin-top: 10px;">
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
         <el-table :data="roleData" border style="width: 100%">
    <el-table-column type="index" label="序号" align="center" width="70" />
    <el-table-column prop="roleName" label="角色名称" align="center" />
    <el-table-column prop="permissionName" label="拥有权限" align="center" />
    <el-table-column prop="status" label="状态" align="center">
          <template #default="scoped">
            <el-tag v-if="scoped.row.status == '0'" type="success">启用</el-tag>
            <el-tag v-else type="danger">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" align="center" >
            <template v-slot="scoped">
          {{ moment(scoped.row.createTime).format("YYYY-MM-DD HH:mm:ss") }}
        </template>
    </el-table-column>
    <el-table-column label="编辑角色" align="center">
        <template #default="scoped">
            <el-button  type="danger" size="small" @click="deleteRole(scoped.row.id)">删除</el-button>
            <el-button  type="primary" size="small" @click="editRole(scoped.row)">编辑</el-button>
        </template>
    </el-table-column>
  </el-table>
  <table>
    <tbody>
        <tr>
            <td>
                <el-pagination
      v-model:current-page="page.PageIndex"
      v-model:page-size="page.PageSize"
      :page-sizes="[1, 2, 3, 4,5]"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="page.totalCount"
    />
            </td>
        </tr>
    </tbody>
  </table>
       </el-card>
       
       <!-- 添加/编辑角色弹窗 -->
       <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" draggable>
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="addRules" label-width="100px">
            <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="ruleForm.roleName" placeholder="请输入角色名称" />
            </el-form-item>
            <!-- <el-form-item label="权限" prop="permissionUrl">
                <el-input v-model="ruleForm.permissionIds" placeholder="请输入权限URL" />
            </el-form-item> -->
            <el-form-item label="权限" prop="permissionIds">
      <el-checkbox-group v-model="ruleForm.permissionIds">
        <el-checkbox v-for="item in permissionData" :value="item.permissionId" :label="item.permissionName" name="type">
        </el-checkbox>
      </el-checkbox-group>
    </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
            </span>
        </template>
    </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref,watch } from 'vue'
import { ElMessageBox } from 'element-plus';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { useRouter } from 'vue-router'
import { useCounterStore } from "@/stores/counter"
import { dataRead, dataWrite } from '@/Utils/Http';
import { ArrowRight } from '@element-plus/icons-vue'
import moment from 'moment';

// 类型定义
interface RuleForm  {
    roleId: number;
    roleName: string;
    permissionIds: [];
}
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
    roleId:0,
    roleName: '',
    permissionIds: []
})

// 变量初始化
const counter = useCounterStore();
const router = useRouter();
const roleData = ref<any>([]);
const searchData = reactive({
    RoleName: ''
});
const page = reactive({
    PageIndex: 1,
    PageSize: 5,
    totalCount: 0,
    pageCount: 0
});

// 弹窗相关
const dialogVisible = ref(false);
const dialogTitle = ref('添加权限');
const formRef = ref<FormInstance>();
// const formData = reactive<FormData>({
//     permissionId: 0,
//     permissionName: '',
//     permissionUrl: ''
// });

// 添加表单验证规则（需要非空验证）
const addRules  = reactive<FormRules<RuleForm>>({
    roleName: [
        { required: true, message: '请输入权限名称', trigger: 'blur' }
    ],
    permissionIds: [
        //{ required: true, message: '请输入权限URL', trigger: 'blur' }
    ]
});

// 编辑表单验证规则（不需要非空验证）
const editRules  = reactive<FormRules<RuleForm>>({});

// 生命周期钩子
onMounted(() => {
    getRoles();
    bindpermission()
});

// 获取权限列表
const getRoles = () => {
    // 模拟数据，实际项目中应替换为真实API调用
    // 这里使用模拟数据以便页面展示
    // permissionData.value = [
    //     { id: 1, name: '试题管理', url: '//' },
    //     { id: 2, name: '考试', url: '//' },
    //     { id: 3, name: '查看成绩', url: '//' },
    //     { id: 4, name: '成绩分析', url: '//' }
    // ];
    
    // 实际API调用代码如下（注释掉）
    dataRead.get('/BaseData/RoleQuery', {
        params: {
            roleName: searchData.RoleName,
            PageIndex: page.PageIndex,
            PageSize: page.PageSize
        } 
    }).then(res => {
        roleData.value = res.data.data.data;
        page.totalCount = res.data.data.totalCount;
        page.pageCount = res.data.data.pageCount;
    }).catch(err => {
        ElMessage.error('获取权限列表失败');
        console.error(err);
    });
};
watch(page, () => {
    getRoles()
})

const permissionData=ref<any>([])
const bindpermission = () => {
    dataRead.get('/BaseData/BindPermission').then(res => {
        permissionData.value=res.data.data
    })
}
// 添加角色
const addPermission = () => {
    dialogTitle.value = '添加角色';
    ruleForm.roleId = 0;
    ruleForm.roleName = '';
    ruleForm.permissionIds = [];
    dialogVisible.value = true;
};

// 编辑角色
const editRole = (row: any) => {
    dialogTitle.value = '编辑角色';
    ruleForm.permissionIds=row.permissionId
   Object.assign(ruleForm,row)
    dialogVisible.value = true;
};

// 删除角色
const deleteRole = (id: number) => {
    ElMessageBox.confirm(
        '确定要删除该角色吗？',
        '删除确认',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(() => {
        ElMessage.error('待完善功能!!!')
        return
        /* 实际API调用代码如下（注释掉）
        dataRead.post('/BaseData/PermissionDelete', { id }).then(res => {
            if (res.data.success) {
                ElMessage.success('删除成功');
                getPermissions(); // 重新获取列表
            } else {
                ElMessage.error(res.data.message || '删除失败');
            }
        }).catch(err => {
            ElMessage.error('删除失败');
            console.error(err);
        });
        */
    }).catch(() => {
        ElMessage.info('已取消删除');
    });
};


// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
        console.log('submit!')
        
        if (ruleForm.roleId == 0)
        {
            if (ruleForm.permissionIds.length == 0)
            {
                ElMessage.error('权限不能为空!!!')
                return;
        }
            dataWrite.post('/BaseData/AddRole',ruleForm).then(res => {
                if (res.data.code == 300)
                {
                    ElMessage.success('添加成功')
                    dialogVisible.value = false
                    getRoles()
                }
                 else if (res.data.data == -1)
                {
                    ElMessage.error(res.data.message)
                }
                else
                {
                 ElMessage.error('添加失败')
            }
          })
        }
        //修改
        else
        {
             dataWrite.post('/BaseData/UpdRole',ruleForm).then(res => {
                if (res.data.code == 400)
                {
                    ElMessage.success('修改成功')
                    dialogVisible.value = false
                    getRoles()
                }
                 else if (res.data.data == -1)
                {
                    ElMessage.error(res.data.message)
                }
                else
                {
                 ElMessage.error('修改失败')
            }
          })
       }
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}


</script>

<style scoped>

</style>